<template>
  <div class="oe-review-teacher">
    <top-tip :title="titleList" :goManage="true" :batchid="batchid"></top-tip>
    <div class="oe-manage-content">
      <div class="oe-manage-content__search">
        <span class="oe-search-label">姓名/工号：</span>
        <span class="oe-search-input">
          <a-input v-model="searchName" placeholder="请输入姓名/工号"></a-input>
        </span>
        <a-button type="primary" @click="searchTeacherForType()">查询</a-button>
        <a-button
          type="primary"
          @click="getAddTeacherListForType()"
          v-if="operationList.includes('导入教师')"
        >导入{{ title }}教师</a-button>
        <a-button
          type="primary"
          @click="showManyModal"
          v-if="$route.name == 'reviewTeacher' && operationList.includes('批量设置题型')"
        >批量设置题型</a-button>
        <a-button
          class="oe-btn-delete"
          @click="deleteBatchTeacherForType()"
          v-if="operationList.includes('删除')"
        >批量删除</a-button>
      </div>
      <div class="oe-manage-content__table">
        <a-table
          :columns="columns"
          :dataSource="dataList"
          :rowSelection="tableSelection"
          :pagination="tablePagination"
          @change="onTableChange"
        >
          <span slot="operation" slot-scope="text, record">
            <a-tooltip placement="bottom" v-if="operationList.includes('批量设置题型')">
              <template slot="title">
                <span>批阅题型</span>
              </template>
              <span
                class="oe-table-delete iconfont icon-piyue1"
                @click.stop="rightQuestion(record)"
              ></span>
            </a-tooltip>
            <a-tooltip placement="bottom" v-if="operationList.includes('删除')">
              <template slot="title">
                <span>删除</span>
              </template>
              <span
                class="oe-table-delete iconfont icon-delete"
                @click.stop="deleteTeacherForType(record.Id)"
              ></span>
            </a-tooltip>
            <a-tooltip placement="bottom" v-if="operationList.includes('分配考生')">
              <template slot="title">
                <span>分配监考学生</span>
              </template>
              <span
                class="oe-table-delete iconfont icon-jinru"
                @click.stop="clickAction(record.TeacherId)"
              ></span>
            </a-tooltip>
          </span>
        </a-table>
      </div>
    </div>

    <a-modal title="选择批阅题型" class="oe-review-modal" centered v-model="visible">
      <div class="oe-review-name">教师姓名：{{ teacherInfo.DisplayName }}</div>
      <div class="oe-review-name">
        批阅题型：
        <a-select
          mode="multiple"
          style="width:calc(100% - 100px)"
          placeholder="请选择题型"
          v-model="selectValue"
          optionLabelProp="label"
        >
          <a-select-option value="5" label="填空题">填空题</a-select-option>
          <a-select-option value="6" label="问答题">问答题</a-select-option>
          <a-select-option value="8" label="阅读理解问答题">阅读理解问答题</a-select-option>
          <a-select-option value="9" label="完型填空问答题">完型填空问答题</a-select-option>
        </a-select>
      </div>
      <div class="oe-review-name">
        显示设置：
        <span class="oe-set-item__select">
          <a-checkbox
            value="IsAnonymous"
            :checked="IsAnonymous"
            @change="IsAnonymous = !IsAnonymous"
          >匿名批阅，不显示学生姓名</a-checkbox>
        </span>
      </div>

      <div slot="footer">
        <a-button type="primary" @click="setMarkQuesType()">确认</a-button>
        <a-button @click.stop="markQuesCancel()">取消</a-button>
      </div>
    </a-modal>
    <!-- 批量设置题型 -->
    <a-modal
      title="批量设置批阅题型"
      class="oe-review-modal"
      centered
      v-model="manyVisible"
      :afterClose="importedCancel"
    >
      <div class="oe-review-name">
        批阅题型：
        <a-select
          mode="multiple"
          style="width:calc(100% - 100px)"
          placeholder="请选择题型"
          v-model="selectModalValue"
          optionLabelProp="label"
        >
          <a-select-option value="5" label="填空题">填空题</a-select-option>
          <a-select-option value="6" label="问答题">问答题</a-select-option>
          <a-select-option value="8" label="阅读理解问答题">阅读理解问答题</a-select-option>
          <a-select-option value="9" label="完型填空问答题">完型填空问答题</a-select-option>
        </a-select>
      </div>
      <div class="oe-review-name">
        显示设置：
        <span class="oe-set-item__select">
          <a-checkbox
            value="IsAnonymous"
            :checked="IsAnonymous"
            @change="IsAnonymous = !IsAnonymous"
          >匿名批阅，不显示学生姓名</a-checkbox>
        </span>
      </div>

      <div slot="footer">
        <a-button type="primary" @click="setMayMarkQuesType">确认</a-button>
        <a-button @click.stop="manyVisible = false">取消</a-button>
      </div>
    </a-modal>
    <!-- 导入监考/批阅教师 -->
    <a-modal
      :title="importTitle"
      class="oe-student"
      :visible="importTeacherModal"
      width="70%"
      @cancel="importedCancel"
    >
      <div class="oe-select">
        <span class="oe-select-input">
          <a-input placeholder="请输入教师名称或工号" v-model="searchName" />
        </span>
        <a-button type="primary" @click.stop="searchAddTeacherForType()">查询</a-button>
      </div>
      <div class="oe-select-table">
        <a-table
          :columns="importedColumns"
          :dataSource="importDataList"
          :scroll="{ y: 240 }"
          :rowSelection="modalSelection"
          :pagination="modalPagination"
          @change="onModalChange"
        ></a-table>
      </div>
      <template slot="footer">
        <a-button @click="addTeacherListForType()" type="primary" html-type="submit">确定</a-button>
        <a-button @click.stop="importedCancel">取消</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import topTip from '@/components/top-tip/index.vue';
import GetOperationList from '@/lib/mixin/methods.js';
export default {
  mixins: [GetOperationList],
  name: 'reviewTeacher',
  components: {
    topTip
  },
  data() {
    return {
      // table分页配置
      tablePagination: {
        pageSizeOptions: ['10', '20', '50', '100', '1000'],
        showSizeChanger: true,
        showTotal(total) {
          return `共 ${total} 条`;
        },
        onShowSizeChange: (current, pageSize) => {
          this.tablePagination.current = current;
          this.tablePagination.pageSize = pageSize;
        },
        onChange: (current, pageSize) => {
          this.tablePagination.current = current;
          this.tablePagination.pageSize = pageSize;
        },
        buildOptionText(props) {
          return props.value + '条/页';
        },
        current: 1,
        pageSize: 10,
        total: 0
      },
      // modal弹窗分页配置
      modalPagination: {
        pageSizeOptions: ['10', '20', '50', '100', '1000'],
        showSizeChanger: true,
        showTotal(total) {
          return `共 ${total} 条`;
        },
        onShowSizeChange: (current, pageSize) => {
          this.modalPagination.current = current;
          this.modalPagination.pageSize = pageSize;
        },
        onChange: (current, pageSize) => {
          this.modalPagination.current = current;
          this.modalPagination.pageSize = pageSize;
        },
        buildOptionText(props) {
          return props.value + '条/页';
        },
        current: 1,
        pageSize: 10,
        total: 0
      },
      // 表标题
      columns: [
        {
          title: '序号',
          dataIndex: 'number',
          width: '10%',
          key: 'number'
        },
        {
          title: '姓名',
          dataIndex: 'DisplayName',
          width: '13%',
          key: 'DisplayName'
        },
        {
          title: '工号',
          dataIndex: 'UserNo',
          width: '10%',
          key: 'UserNo'
        },
        {
          title: '用户名',
          dataIndex: 'UserName',
          width: '10%',
          key: 'UserName'
        },
        {
          title: '院校',
          dataIndex: 'SchoolName',
          width: '15%',
          key: 'SchoolName'
        },
        {
          title: '批阅题型',
          dataIndex: 'QuestionTypeText',
          width: '15%',
          key: 'QuestionTypeText'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '10%',
          key: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      // 数据列表
      dataList: [],
      visible: false,
      IsAnonymous: false,
      // 点击的用户
      teacherInfo: {},
      // 选择的值
      selectValue: [],
      //搜索
      searchName: '',
      //导入教师
      importedColumns: [
        {
          title: '序号',
          dataIndex: 'number',
          align: 'center'
        },
        {
          title: '教师名称',
          dataIndex: 'DisplayName',
          sorter: true,
          align: 'center'
        },
        {
          title: '教师工号',
          dataIndex: 'UserNo',
          sorter: true,
          align: 'center'
        },
        {
          title: '所属院校',
          dataIndex: 'SchoolName',
          sorter: true,
          align: 'center'
        }
      ],
      importDataList: [],
      selectedRowKeys: [],
      importTeacherModal: false,
      getType: 0,
      modalDefaultKey: [],
      modalRowSelect: [],
      tableDefaultKey: [],
      tableRowSelect: [],
      // 操作List
      operationList: [],
      IsOpList: [],
      manyVisible: false,
      selectModalValue: []
    };
  },
  props: {
    examid: {
      type: String,
      default: ''
    },
    batchid: {
      type: String,
      default: ''
    }
  },
  computed: {
    title() {
      if (this.$route.name == 'proctorTeacher') {
        return `监考`;
      } else {
        return `批阅`;
      }
    },
    titleList() {
      if (this.$route.name == 'proctorTeacher') {
        return [{ text: '考试管理' }, { text: '监考教师', color: '#0177D5' }];
      } else {
        return [{ text: '考试管理' }, { text: '批阅教师', color: '#0177D5' }];
      }
    },
    //获取当前路由名称
    type() {
      return this.$route.name;
    },
    importTitle() {
      if (this.$route.name == 'proctorTeacher') {
        return `导入监考教师`;
      } else {
        return `导入批阅教师`;
      }
    },
    modalSelection() {
      const { modalDefaultKey } = this;
      return {
        selectedRowKeys: modalDefaultKey,
        onChange: this.onModalSelectChange
      };
    },
    tableSelection() {
      const { tableDefaultKey } = this;
      return {
        selectedRowKeys: tableDefaultKey,
        onChange: this.onTableSelectChange
      };
    }
  },
  mounted() {
    this.getOpeartion();
  },
  methods: {
    /*************权限判断******************************/
    // 判断是否是只读
    getIsWrite(type) {
      let index = this.IsOpList.findIndex((el) => {
        return el.Name === type;
      });
      if (index > -1) {
        if (this.IsOpList[index].IsRead && !this.IsOpList[index].IsWrite) {
          this.$message.info('您没有该操作权限！');
          return false;
        } else {
          return true;
        }
      }
    },
    // 获取页面操作
    getOpeartion() {
      this.loading = true;
      this.GetOperationList().then((rst) => {
        this.loading = false;
        this.operationList = [];
        this.IsOpList = [];
        if (rst.code === 1) {
          if (rst.list.length) {
            rst.list.forEach((item) => {
              this.operationList.push(item.Name);
              this.IsOpList = rst.list;
            });
          }
          this.getTeacherListForType();
        } else {
          this.$message.error(rst.msg);
        }
      });
    },

    /***************************获取教师列表***************************************** */
    //获取已添加老师列表
    getTeacherListForType() {
      if (this.$route.name === 'proctorTeacher') {
        this.getProctorTeacherList();
        if (this.columns.length == 8) {
          this.columns.splice(5, 1);
        }
      } else {
        this.getReviewTeacherList();
      }
    },
    //获取监考老师列表
    getProctorTeacherList(current, pageSize, sort) {
      var that = this;
      this.getType = 0;
      this.$http
        .post('/api/examMonitor/ExamMonitor/getMonitorTeaList', {
          getType: this.getType,
          examId: this.examid,
          sort: '',
          key: this.searchName,
          schoolName: '',
          page: current || 1,
          pageSize: pageSize || 10
        })
        .then((rst) => {
          if (rst.code > 0) {
            this.dataList = [];
            this.tablePagination.current = rst.pagination.pageIndex;
            this.tablePagination.pageSize = rst.pagination.pageSize;
            this.tablePagination.total = rst.pagination.totalCount;
            this.searchName = '';

            if (rst.list.length) {
              rst.list.forEach((item, index) => {
                let number = (rst.pagination.pageIndex - 1) * rst.pagination.pageSize + index + 1;
                this.dataList.push({
                  ...item,
                  number: number
                });
              });
            }
          } else {
            that.$message.warning(rst.msg);
          }
        });
    },
    //获取批阅老师列表
    getReviewTeacherList(current, pageSize, sort) {
      var that = this;
      this.getType = 0;
      this.$http
        .post('/api/design/Marking/getTeaList', {
          getType: this.getType,
          examId: this.examid,
          key: this.searchName,
          schoolName: '',
          page: current || 1,
          pageSize: pageSize || 10
        })
        .then((rst) => {
          if (rst.code > 0) {
            this.dataList = [];
            this.tablePagination.current = rst.pagination.pageIndex;
            this.tablePagination.pageSize = rst.pagination.pageSize;
            this.tablePagination.total = rst.pagination.totalCount;
            this.searchName = '';

            if (rst.list.length) {
              rst.list.forEach((item, index) => {
                let number = (rst.pagination.pageIndex - 1) * rst.pagination.pageSize + index + 1;
                this.dataList.push({
                  ...item,
                  number: number
                });
              });
            }
          } else {
            that.$message.warning(rst.msg);
          }
        });
    },
    // 点击table分页，排序
    onTableChange(pagenation, filter, sort) {
      let sortOrder = '';
      if (sort.order) {
        if (sort.order == 'ascend') {
          sortOrder = sort.columnKey;
        } else if (sort.order == 'descend') {
          sortOrder = '-' + sort.columnKey;
        } else {
          sortOrder = '';
        }
      }
      if (this.$route.name == 'proctorTeacher') {
        this.getProctorTeacherList(pagenation.current, pagenation.pageSize, sortOrder);
      } else {
        this.getReviewTeacherList(pagenation.current, pagenation.pageSize, sortOrder);
      }
    },
    //查询教师
    searchTeacherForType() {
      if (this.$route.name == 'proctorTeacher') {
        this.getProctorTeacherList();
      } else {
        this.getReviewTeacherList();
      }
    },
    /**************************获取待添加教师列表****************************** */
    //获取待添加的教师列表
    getAddTeacherListForType() {
      // debugger;
      if (!this.getIsWrite('导入教师')) {
        return;
      }
      if (this.$route.name == 'proctorTeacher') {
        this.getAddProctorTeacherList();
        this.importTeacherModal = true;
      } else {
        this.importTeacherModal = true;
        this.getAddReviewTeacherList();
      }
    },
    //获取待添加监考老师列表
    getAddProctorTeacherList(current, pageSize, sort) {
      // debugger;
      var that = this;
      this.getType = 1;
      this.$http
        .post('/api/examMonitor/ExamMonitor/getMonitorTeaList', {
          getType: this.getType,
          examId: this.examid,
          key: this.searchName,
          schoolName: '',
          page: current || 1,
          pageSize: pageSize || 10
        })
        .then((rst) => {
          if (rst.code > 0) {
            this.importDataList = [];
            this.modalPagination.current = rst.pagination.pageIndex;
            this.modalPagination.pageSize = rst.pagination.pageSize;
            this.modalPagination.total = rst.pagination.totalCount;
            this.searchName = '';
            if (rst.list.length) {
              rst.list.forEach((item, index) => {
                let number = (rst.pagination.pageIndex - 1) * rst.pagination.pageSize + index + 1;
                this.importDataList.push({
                  ...item,
                  key: number,
                  number: number
                });
              });
            }
          } else {
            that.$message.warning(rst.msg);
          }
        });
    },
    //获取待添加批阅老师列表
    getAddReviewTeacherList(current, pageSize, sort) {
      var that = this;
      this.getType = 1;
      this.$http
        .post('/api/design/Marking/getTeaList', {
          getType: this.getType,
          examId: this.examid,
          sort: sort,
          key: this.searchName,
          schoolName: '',
          page: current || 1,
          pageSize: pageSize || 10
        })
        .then((rst) => {
          if (rst.code > 0) {
            this.importDataList = [];
            this.modalPagination.current = rst.pagination.pageIndex;
            this.modalPagination.pageSize = rst.pagination.pageSize;
            this.modalPagination.total = rst.pagination.totalCount;
            this.searchName = '';
            if (rst.list.length) {
              rst.list.forEach((item, index) => {
                let number = (rst.pagination.pageIndex - 1) * rst.pagination.pageSize + index + 1;
                this.importDataList.push({
                  ...item,
                  key: number,
                  number: number
                });
              });
            }
          } else {
            that.$message.warning(rst.msg);
          }
        });
    },
    // 点击modal分页，排序
    onModalChange(pagenation, filter, sort) {
      let sortOrder = '';
      if (sort.order) {
        if (sort.order == 'ascend') {
          sortOrder = sort.columnKey;
        } else if (sort.order == 'descend') {
          sortOrder = '-' + sort.columnKey;
        } else {
          sortOrder = '';
        }
      }
      if (this.$route.name == 'proctorTeacher') {
        this.getAddProctorTeacherList(pagenation.current, pagenation.pageSize, sortOrder);
      } else {
        this.getAddReviewTeacherList(pagenation.current, pagenation.pageSize, sortOrder);
      }
    },
    // 获取modal选择的
    onModalSelectChange(selectedRowKeys, selectedRow) {
      this.modalDefaultKey = selectedRowKeys;
      this.modalRowSelect = selectedRow;
    },
    //查询添加教师
    searchAddTeacherForType() {
      if (this.$route.name == 'proctorTeacher') {
        this.getAddProctorTeacherList();
      } else {
        this.getAddReviewTeacherList();
      }
    },
    /**************************添加教师****************************** */
    //添加教师
    addTeacherListForType() {
      if (this.$route.name == 'proctorTeacher') {
        this.addProctorTeacher();
      } else {
        this.addReviewTeacher();
      }
    },
    //添加监考教师
    addProctorTeacher() {
      if (!this.modalRowSelect.length) {
        this.$message.warning(`请选择要添加的教师`);
        return;
      }
      this.loading = true;
      let ids = [];
      this.modalRowSelect.forEach((item) => {
        ids.push(item.Id);
      });
      this.loading = true;
      var that = this;
      this.$http
        .post('/api/examMonitor/ExamMonitor/addMarkTea', {
          ids,
          examId: this.examid
        })
        .then((rst) => {
          if (rst.code > 0) {
            that.$message.success(rst.msg);
            that.getTeacherListForType();
            that.importedCancel();
          } else {
            that.$message.warning(rst.msg);
          }
        });
    },
    //添加批阅教师
    addReviewTeacher() {
      if (!this.modalRowSelect.length) {
        this.$message.warning(`请选择要添加的教师`);
        return;
      }
      this.loading = true;
      let ids = [];
      this.modalRowSelect.forEach((item) => {
        ids.push(item.Id);
      });
      this.loading = true;
      var that = this;
      this.$http
        .post('/api/design/Marking/addMarkTea', {
          ids,
          examId: this.examid
        })
        .then((rst) => {
          if (rst.code > 0) {
            that.$message.success(rst.msg);
            that.getTeacherListForType();
            that.importedCancel();
            this.displayCancel();
          } else {
            that.$message.warning(rst.msg);
          }
        });
    },
    /**************************删除教师****************************** */
    //批量删除数据
    deleteBatchTeacherForType() {
      if (!this.getIsWrite('删除')) {
        return;
      }
      if (this.$route.name === 'proctorTeacher') {
        this.deleteBatchProctorTeacher();
      } else {
        this.deleteBatchReviewTeacher();
      }
    },
    //批量删除监考老师
    deleteBatchProctorTeacher() {
      if (!this.tableRowSelect.length) {
        this.$message.warning(`请选择要删除的教师`);
        return;
      }
      this.loading = true;
      let ids = [];
      this.tableRowSelect.forEach((item) => {
        ids.push(item.Id);
      });
      this.loading = true;
      this.deleteProctorTeacher(ids);
    },
    //批量删除批阅老师
    deleteBatchReviewTeacher() {
      if (!this.tableRowSelect.length) {
        this.$message.warning(`请选择要删除的教师`);
        return;
      }
      this.loading = true;
      let ids = [];
      this.tableRowSelect.forEach((item) => {
        ids.push(item.Id);
      });
      this.loading = true;
      this.deleteReviewTeacher(ids);
    },
    //单个删除数据
    deleteTeacherForType(id) {
      if (!this.getIsWrite('删除')) {
        return;
      }
      if (this.$route.name === 'proctorTeacher') {
        this.deleteProctorTeacher(id);
      } else {
        this.deleteReviewTeacher(id);
      }
    },
    // 点击操作
    clickAction(teacherId) {
      this.$router.push({
        name: 'examMonitorStu',
        params: {
          examid: this.examid,
          teacherid: teacherId
        }
      });
    },
    //删除监考老师
    deleteProctorTeacher(id) {
      var that = this;
      this.$http
        .post('/api/examMonitor/ExamMonitor/deleteTea', {
          ids: id,
          examId: this.examid
        })
        .then((rst) => {
          if (rst.code > 0) {
            this.getTeacherListForType();
            this.displayCancel();
            that.$message.success(rst.msg);
          } else {
            that.$message.warning(rst.msg);
          }
        });
    },
    //删除批阅教师
    deleteReviewTeacher(id) {
      var that = this;
      this.$http
        .post('/api/design/Marking/deleteTea', {
          ids: id,
          examId: this.examid
        })
        .then((rst) => {
          if (rst.code > 0) {
            that.$message.success(rst.msg);
            this.getTeacherListForType();
            this.displayCancel();
          } else {
            that.$message.warning(rst.msg);
          }
        });
    },

    //获取table选择数据
    onTableSelectChange(selectedRowKeys, selectedRow) {
      this.tableDefaultKey = selectedRowKeys;
      this.tableRowSelect = selectedRow;
    },

    importedCancel() {
      this.importTeacherModal = false;
      this.searchName = '';
      this.modalDefaultKey = [];
      this.modalRowSelect = [];
      this.tableDefaultKey = [];
      this.tableRowSelect = [];
      this.selectModalValue = [];
    },
    // 批阅题目
    rightQuestion(row) {
      if (!this.getIsWrite('批量设置题型')) {
        return;
      }
      console.log(row);
      this.teacherInfo = row;
      this.IsAnonymous = false;
      this.IsAnonymous = row.IsAnonymous;
      this.visible = true;
      if (this.teacherInfo.MarkTeaQueType[0]) {
        this.selectValue = this.teacherInfo.MarkTeaQueType;
      } else {
        this.selectValue = [];
      }
    },
    //设置老师批阅题型
    setMarkQuesType() {
      var that = this;
      this.loading = true;
      this.$http
        .post('/api/design/Marking/setMarkTeaQueType', {
          examId: this.examid,
          userIds: this.teacherInfo.Id,
          type: this.selectValue.toString(),
          anonymousType: this.IsAnonymous
        })
        .then((rst) => {
          this.loading = false;
          if (this.selectValue) {
            if (rst.code > 0) {
              that.$message.success(rst.msg);
              this.getReviewTeacherList();
              this.visible = false;
              this.teacherInfo = [];
              this.selectValue = [];
            } else {
              that.$message.error(rst.msg);
            }
          } else {
            that.$message.warning(rst.msg);
          }
        });
    },
    // 批量设置老师批阅题型
    setMayMarkQuesType() {
      this.loading = true;
      let tIds = [];
      this.tableRowSelect.forEach((item) => {
        tIds.push(item.Id);
      });
      this.$http
        .post('/api/design/Marking/setMarkTeaQueType', {
          examId: this.examid,
          userIds: tIds,
          type: this.selectModalValue.toString(),
          anonymousType: this.IsAnonymous
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code > 0) {
            this.manyVisible = false;
            this.$message.success(rst.msg);
            this.getTeacherListForType();
            this.displayCancel();
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    markQuesCancel() {
      this.visible = false;
      this.teacherInfo = [];
      this.selectValue = [];
    },
    // 显示批量设置题型的
    showManyModal() {
      if (!this.getIsWrite('批量设置题型')) {
        return;
      }
      if (!this.tableRowSelect.length) {
        this.$message.error('请先选择你要进行批量设置批阅题型的老师！');
        return;
      }
      this.IsAnonymous = false;
      this.manyVisible = true;
    },
    // 重置状态
    displayCancel() {
      this.searchName = '';
      this.modalDefaultKey = [];
      this.modalRowSelect = [];
      this.tableDefaultKey = [];
      this.tableRowSelect = [];
    }
  }
};
</script>
